let departments = [];
let users = [];
let selectedDepartment = null;
let isEditMode = false;
let currentDepartmentId = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', async function() {
    // 检查认证状态
    if (window.AuthManager && window.AuthManager.getUserInfo()) {
        window.PermissionManager.init(window.AuthManager.getUserInfo());
    }
    
    const checkAuth = () => {
        if (window.AuthManager) {
            initDepartmentPage();
        } else {
            setTimeout(checkAuth, 100);
        }
    };
    checkAuth();

    if (window.PermissionManager) {
        PermissionManager.initDepartmentPermissions();
    }
});

// 初始化部门管理页面
async function initDepartmentPage() {
    console.log('开始初始化部门管理页面...');
    console.log('AuthManager:', window.AuthManager);
    
    const userInfo = window.AuthManager.getUserInfo();
    console.log('用户信息:', userInfo);
    
    if (!userInfo) {
        console.log('未找到用户信息，重定向到登录页面');
        window.location.href = '/ercms/login';
        return;
    }

    // 检查用户权限
    console.log('检查用户权限，用户角色:', userInfo.role);
    if (!window.AuthManager.hasAnyRole(['ADMIN', 'DEPT_MANAGER'])) {
        console.log('用户权限不足，重定向到仪表盘');
        alert('您没有权限访问部门管理页面');
        window.location.href = '/ercms/dashboard';
        return;
    }

    console.log('用户认证成功，开始加载部门管理页面');
    
    // 先加载用户数据，再加载部门数据
    await loadUsers();
    await loadDepartments();
}

// 加载部门数据
async function loadDepartments() {
    try {
        const headers = window.AuthManager.getAuthHeaders();
        const response = await fetch('/ercms/api/departments/tree', {
            headers: headers
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = await response.json();
        if (result.success) {
            departments = result.data;
            console.log('部门数据加载成功，共加载', departments.length, '个顶级部门');
            renderDepartmentTree();
        } else {
            console.error('部门数据加载失败：', result.message);
            alert('加载部门数据失败：' + result.message);
        }
    } catch (error) {
        console.error('加载部门数据失败：', error);
        alert('加载部门数据失败，请刷新页面重试');
    }
}

// 加载用户数据
async function loadUsers() {
    try {
        const headers = window.AuthManager.getAuthHeaders();
        const response = await fetch('/ercms/api/users', {
            headers: headers
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const usersData = await response.json();
        // UserController 返回包装格式 {success: true, data: [...]}
        if (usersData.success && Array.isArray(usersData.data)) {
            users = usersData.data;
            console.log('用户数据加载成功，共加载', users.length, '个用户');
            populateUserSelects();
        } else {
            console.error('用户数据格式错误：', usersData);
            throw new Error('用户数据格式错误');
        }
    } catch (error) {
        console.error('加载用户数据失败：', error);
        alert('加载用户数据失败，请刷新页面重试');
    }
}

// 渲染部门树
function renderDepartmentTree() {
    const treeContainer = document.getElementById('departmentTree');
    if (!treeContainer) {
        console.error('找不到部门树容器');
        return;
    }
    
    treeContainer.innerHTML = '';
    
    if (!departments || departments.length === 0) {
        console.warn('部门数据为空');
        treeContainer.innerHTML = '<div class="text-center text-muted">暂无部门数据</div>';
        return;
    }
    
    console.log('开始渲染部门树，共', departments.length, '个顶级部门');
    
    departments.forEach(dept => {
        const deptElement = createDepartmentElement(dept);
        treeContainer.appendChild(deptElement);
    });
}

// 创建部门元素
function createDepartmentElement(department) {
    if (!department) {
        console.error('部门对象为空');
        return document.createElement('div');
    }
    
    const div = document.createElement('div');
    div.className = 'department-item';
    div.onclick = () => selectDepartment(department);
    
    const icon = department.children && department.children.length > 0 ? 'bi-folder-fill' : 'bi-building';
    const color = department.children && department.children.length > 0 ? 'text-warning' : 'text-primary';
    
    div.innerHTML = `
        <div class="d-flex align-items-center">
            <i class="bi ${icon} ${color} department-icon"></i>
            <span class="flex-grow-1">${department.name || '未命名部门'}</span>
            <div class="btn-group btn-group-sm" onclick="event.stopPropagation()">
                <button class="btn btn-outline-primary btn-sm" onclick="showEditDepartmentModal(${department.id})">
                    <i class="bi bi-pencil"></i>
                </button>
                <button class="btn btn-outline-danger btn-sm" onclick="deleteDepartment(${department.id})">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        </div>
    `;
    
    if (department.children && department.children.length > 0) {
        const childrenDiv = document.createElement('div');
        childrenDiv.className = 'department-children';
        department.children.forEach(child => {
            const childElement = createDepartmentElement(child);
            childrenDiv.appendChild(childElement);
        });
        div.appendChild(childrenDiv);
    }
    
    return div;
}

// 选择部门
function selectDepartment(department) {
    if (!department) {
        console.error('部门对象为空');
        return;
    }
    
    console.log('选择部门:', department.name, 'ID:', department.id);
    
    selectedDepartment = department;
    
    // 更新选中状态
    document.querySelectorAll('.department-item').forEach(item => {
        item.classList.remove('selected');
    });
    event.currentTarget.classList.add('selected');
    
    // 显示部门详情
    showDepartmentDetails(department);
}

// 显示部门详情
function showDepartmentDetails(department) {
    const detailsContainer = document.getElementById('departmentDetails');
    
    if (!department) {
        console.error('部门对象为空');
        return;
    }
    
    const managerName = department.managerName || '未设置';
    const parentName = department.parentName || '无';
    
    console.log('显示部门详情:', department.name, '管理员:', managerName, '上级部门:', parentName);
    
    detailsContainer.innerHTML = `
        <div class="row">
            <div class="col-md-6">
                <h6>基本信息</h6>
                <table class="table table-borderless">
                    <tr>
                        <td><strong>部门名称：</strong></td>
                        <td>${department.name}</td>
                    </tr>
                    <tr>
                        <td><strong>部门描述：</strong></td>
                        <td>${department.description || '无'}</td>
                    </tr>
                    <tr>
                        <td><strong>上级部门：</strong></td>
                        <td>${parentName}</td>
                    </tr>
                    <tr>
                        <td><strong>部门管理员：</strong></td>
                        <td>${managerName}</td>
                    </tr>
                    <tr>
                        <td><strong>创建时间：</strong></td>
                        <td>${new Date(department.createdAt).toLocaleString()}</td>
                    </tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6>操作</h6>
                <div class="d-grid gap-2">
                    <button class="btn btn-primary" onclick="showEditDepartmentModal(${department.id})">
                        <i class="bi bi-pencil"></i> 编辑部门
                    </button>
                    <button class="btn btn-info" onclick="showManagerModal(${department.id})">
                        <i class="bi bi-person-gear"></i> 设置管理员
                    </button>
                    <button class="btn btn-success" onclick="showCreateDepartmentModal(${department.id})">
                        <i class="bi bi-plus"></i> 创建子部门
                    </button>
                    <button class="btn btn-danger" onclick="deleteDepartment(${department.id})">
                        <i class="bi bi-trash"></i> 删除部门
                    </button>
                </div>
            </div>
        </div>
    `;
}

// 填充用户选择框
function populateUserSelects() {
    const managerSelect = document.getElementById('departmentManager');
    const newManagerSelect = document.getElementById('newManager');
    const parentSelect = document.getElementById('parentDepartment');
    
    // 清空现有选项
    managerSelect.innerHTML = '<option value="">请选择管理员</option>';
    newManagerSelect.innerHTML = '<option value="">请选择管理员</option>';
    parentSelect.innerHTML = '<option value="">无（顶级部门）</option>';
    
    // 确保users数组已加载
    if (!users || users.length === 0) {
        console.warn('用户数据尚未加载完成');
        return;
    }
    
    // 添加用户选项（只显示管理员角色的用户）
    let managerCount = 0;
    users.forEach(user => {
        if (user.enabled && (user.role === 'DEPT_MANAGER' || user.role === 'ADMIN')) {
            const option = `<option value="${user.id}">${user.realName} (${user.username})</option>`;
            managerSelect.innerHTML += option;
            newManagerSelect.innerHTML += option;
            managerCount++;
        }
    });
    
    console.log('填充用户选择框完成，找到', managerCount, '个管理员用户');
    
    // 添加部门选项（排除当前编辑的部门及其子部门）
    populateParentDepartmentOptions(parentSelect, currentDepartmentId);
}

// 填充上级部门选择框
function populateParentDepartmentOptions(selectElement, excludeId = null) {
    if (!selectElement) {
        console.error('选择框元素为空');
        return;
    }
    
    if (!departments || departments.length === 0) {
        console.warn('部门数据为空，无法填充上级部门选项');
        return;
    }
    
    function addDepartmentOptions(departments, level = 0) {
        departments.forEach(dept => {
            // 排除当前编辑的部门及其子部门
            if (excludeId && (dept.id === excludeId || isChildOf(dept.id, excludeId))) {
                return;
            }
            
            const prefix = '　'.repeat(level); // 使用全角空格缩进
            const option = `<option value="${dept.id}">${prefix}${dept.name || '未命名部门'}</option>`;
            selectElement.innerHTML += option;
            
            if (dept.children && dept.children.length > 0) {
                addDepartmentOptions(dept.children, level + 1);
            }
        });
    }
    
    addDepartmentOptions(departments);
}

// 检查部门是否为指定部门的子部门
function isChildOf(departmentId, parentId) {
    if (!departmentId || !parentId) {
        return false;
    }
    
    if (!departments || departments.length === 0) {
        console.warn('部门数据为空，无法检查子部门关系');
        return false;
    }
    
    function checkChildren(departments, targetId) {
        for (let dept of departments) {
            if (dept.id === targetId) {
                return true;
            }
            if (dept.children && dept.children.length > 0) {
                if (checkChildren(dept.children, targetId)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    const parent = findDepartmentById(parentId);
    return parent && parent.children ? checkChildren(parent.children, departmentId) : false;
}

// 显示创建部门模态框
function showCreateDepartmentModal(parentId = null) {
    isEditMode = false;
    currentDepartmentId = null;
    document.getElementById('modalTitle').textContent = '创建部门';
    document.getElementById('departmentForm').reset();
    
    // 确保users数组已加载
    if (!users || users.length === 0) {
        console.warn('用户数据尚未加载完成');
        alert('用户数据加载中，请稍后再试');
        return;
    }
    
    // 重新填充选择框
    populateUserSelects();
    
    if (parentId) {
        document.getElementById('parentDepartment').value = parentId;
    }
    
    const modal = new bootstrap.Modal(document.getElementById('departmentModal'));
    modal.show();
}

// 显示编辑部门模态框
function showEditDepartmentModal(departmentId) {
    const department = findDepartmentById(departmentId);
    if (!department) return;
    
    isEditMode = true;
    currentDepartmentId = departmentId;
    document.getElementById('modalTitle').textContent = '编辑部门';
    
    // 确保users数组已加载
    if (!users || users.length === 0) {
        console.warn('用户数据尚未加载完成');
        alert('用户数据加载中，请稍后再试');
        return;
    }
    
    // 重新填充选择框（排除当前部门及其子部门）
    populateUserSelects();
    
    document.getElementById('departmentName').value = department.name;
    document.getElementById('departmentDescription').value = department.description || '';
    document.getElementById('parentDepartment').value = department.parentId || '';
    document.getElementById('departmentManager').value = department.managerId || '';
    
    const modal = new bootstrap.Modal(document.getElementById('departmentModal'));
    modal.show();
}

// 保存部门
async function saveDepartment() {
    const formData = {
        name: document.getElementById('departmentName').value,
        description: document.getElementById('departmentDescription').value,
        parentId: document.getElementById('parentDepartment').value || null,
        managerId: document.getElementById('departmentManager').value || null
    };
    
    if (!formData.name.trim()) {
        alert('请输入部门名称');
        return;
    }
    
    console.log('保存部门数据:', formData);
    
    try {
        const url = isEditMode ? `/ercms/api/departments/${currentDepartmentId}` : '/ercms/api/departments';
        const method = isEditMode ? 'PUT' : 'POST';
        
        console.log('请求URL:', url, '方法:', method);
        
        const headers = window.AuthManager.getAuthHeaders();
        const response = await fetch(url, {
            method: method,
            headers: headers,
            body: JSON.stringify(formData)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        console.log('保存部门响应:', result);
        
        if (result.success) {
            alert(result.message);
            bootstrap.Modal.getInstance(document.getElementById('departmentModal')).hide();
            loadDepartments();
        } else {
            alert('操作失败：' + result.message);
        }
    } catch (error) {
        console.error('保存部门失败：', error);
        alert('保存部门失败：' + error.message);
    }
}

// 删除部门
async function deleteDepartment(departmentId) {
    if (!departmentId) {
        console.error('部门ID为空');
        return;
    }
    
    if (!confirm('确定要删除这个部门吗？删除后无法恢复！')) {
        return;
    }
    
    console.log('删除部门，ID:', departmentId);
    
    try {
        const headers = window.AuthManager.getAuthHeaders();
        const response = await fetch(`/ercms/api/departments/${departmentId}`, {
            method: 'DELETE',
            headers: headers
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        console.log('删除部门响应:', result);
        
        if (result.success) {
            alert(result.message);
            loadDepartments();
            document.getElementById('departmentDetails').innerHTML = `
                <div class="text-center text-muted">
                    <i class="bi bi-building" style="font-size: 3rem;"></i>
                    <p class="mt-2">请选择一个部门查看详情</p>
                </div>
            `;
        } else {
            alert('删除失败：' + result.message);
        }
    } catch (error) {
        console.error('删除部门失败：', error);
        alert('删除部门失败：' + error.message);
    }
}

// 显示设置管理员模态框
function showManagerModal(departmentId) {
    currentDepartmentId = departmentId;
    
    // 重新填充管理员选择框
    const newManagerSelect = document.getElementById('newManager');
    newManagerSelect.innerHTML = '<option value="">请选择管理员</option>';
    
    // 确保users数组已加载
    if (!users || users.length === 0) {
        console.warn('用户数据尚未加载完成');
        alert('用户数据加载中，请稍后再试');
        return;
    }
    
    // 添加用户选项（只显示管理员角色的用户）
    let managerCount = 0;
    users.forEach(user => {
        if (user.enabled && (user.role === 'DEPT_MANAGER' || user.role === 'ADMIN')) {
            const option = `<option value="${user.id}">${user.realName} (${user.username})</option>`;
            newManagerSelect.innerHTML += option;
            managerCount++;
        }
    });
    
    console.log('设置管理员模态框填充完成，找到', managerCount, '个管理员用户');
    
    // 设置当前管理员为选中状态
    const department = findDepartmentById(departmentId);
    if (department && department.managerId) {
        newManagerSelect.value = department.managerId;
        console.log('设置当前管理员为选中状态:', department.managerId);
    }
    
    const modal = new bootstrap.Modal(document.getElementById('managerModal'));
    modal.show();
}

// 设置管理员
async function setManager() {
    const managerId = document.getElementById('newManager').value;
    console.log('开始设置部门管理员，部门ID:', currentDepartmentId, '管理员ID:', managerId);
    
    try {
        const url = managerId ? 
            `/ercms/api/departments/${currentDepartmentId}/manager?managerId=${managerId}` :
            `/ercms/api/departments/${currentDepartmentId}/manager`;
        
        console.log('请求URL:', url);
        
        const headers = window.AuthManager.getAuthHeaders();
        const response = await fetch(url, {
            method: 'PUT',
            headers: headers
        });
        
        const result = await response.json();
        console.log('设置管理员响应:', result);
        
        if (result.success) {
            alert(result.message);
            bootstrap.Modal.getInstance(document.getElementById('managerModal')).hide();
            loadDepartments();
            // 如果当前选中的部门是正在设置的部门，刷新详情
            if (selectedDepartment && selectedDepartment.id === currentDepartmentId) {
                // 重新加载部门数据后，重新获取最新的部门信息
                setTimeout(() => {
                    const updatedDepartment = findDepartmentById(currentDepartmentId);
                    if (updatedDepartment) {
                        selectedDepartment = updatedDepartment;
                        showDepartmentDetails(updatedDepartment);
                        console.log('部门详情已刷新');
                    }
                }, 100);
            }
        } else {
            alert('设置失败：' + result.message);
        }
    } catch (error) {
        console.error('设置管理员失败：', error);
        alert('设置管理员失败');
    }
}

// 根据ID查找部门
function findDepartmentById(id) {
    if (!id || !departments || departments.length === 0) {
        console.warn('查找部门失败：ID为空或部门数据未加载');
        return null;
    }
    
    function search(deptList) {
        for (let dept of deptList) {
            if (dept.id === id) {
                return dept;
            }
            if (dept.children) {
                const found = search(dept.children);
                if (found) return found;
            }
        }
        return null;
    }
    
    const result = search(departments);
    if (!result) {
        console.warn('未找到ID为', id, '的部门');
    }
    return result;
} 